<?php
namespace Pig\Controller;
use \Pig\Util\Page;

class PlanController extends BaseController {
    public $tca = array();
    public $tbName = CONTROLLER_NAME;

    /**
     * 高级搜索
     + 数据说明
     + label    页面显示数据
     + name     数据库字段名
     + type     搜索类型(目前只支持input及select的搜索)
     + data     select框所有数据(在init函数中赋值,input类型,此项为空)
     + value    接收页面传值并在搜索之后在页面展示
     + category 针对input的类型(normal代表普通的input,time代表时间搜索的input),select类型无此数据
     */
    public $search = array(
    );

    /**
     * 数据操作(权限管理)
     + 数据说明(目前只支持添加,数据导入,数据导出----注意方法名需保持跟权限表的添加的数据一致)
     + label     页面显示操作权限
     + access    操作方法
     + class     页面显示样式
     */
    public $action = array(
        array('label' => '添加', 'access' => 'save', 'class' => 'icon-plus')
    );

    /**
     * 管理操作(权限管理)
     + 数据说明(注意方法名需保持跟权限表的添加的数据一致)
     + label     页面显示操作权限
     + access    操作方法
     */
    public $edit_action = array(
        array('label' => '编辑', 'access' => 'edit', 'class' => 'btn green-stripe mini','type' => 'link'),
        array('label' => '删除', 'access' => 'del', 'class' => 'btn red-stripe mini del', 'type' => 'link')
    );

    /**
     * 操作管理(数据删除,发布,草稿,置顶,不顶,热门,不热等操作)
     + 数据说明(确保数据表中有相关参数,若需要添加特殊操作,应先在BaseController下添加相关操作方法)
     + label     页面显示操作内容
     + access    操作方法
     */
    public $handle = array(
    );

    /**
     * 列表页表头展示内容
     + 数据说明(确保数据表中有相关参数,若需要添加特殊操作,应先在BaseController下添加相关操作方法)
     + label     页面显示操作内容
     + field     字段名
     + status    编辑状态(true为列表页可编辑,false为不能编辑)
     */
    public $index_content = array(
        array('label' => 'ID编号', 'field' => 'id', 'status' => false),
        array('label' => '品牌', 'field' => 'brand_id', 'status' => false,'relation' => ['brand','name']),
        array('label' => '型号', 'field' => 'model_id', 'status' => false,'relation' => ['model','name']),
        array('label' => '故障分类', 'field' => 'category_id', 'status' => false,'relation' => ['category','name']),
        array('label' => '故障详情', 'field' => 'failure_id', 'status' => false,'relation' => ['failure','name']),
        array('label' => '原价', 'field' => 'origin_price', 'status' => false),
        array('label' => '现价', 'field' => 'sale_price', 'status' => false)
    );

    protected function init() {
        //高级筛选
        $this->assign('status_all', $this->status_all);

        //数据操作(权限管理)
        $this->assign('action', $this->action);

        //管理操作
        $this->assign('edit_action', $this->edit_action);

        //操作管理
        $this->assign('handle', $this->handle);

        //列表页表头展示内容
        $this->assign('index_content', $this->index_content);
        
        $info = [];
        if (ACTION_NAME == 'edit') {
            $id = I('param.id');
            $info = M($this->tbName)->where('id = ' . $id)->find();
        } 
        /*品牌*/
        $Brands = M('brand');
        $result_brand = $Brands->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        $brands = '';
        foreach ($result_brand as $key => $value) {
            $select = $value[0] == $info['brand_id']?'selected="selected"':'';
            $brands .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        /*机型*/
        $Model = M('model');
        $models = '';
        $result_model = $Model->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        foreach ($result_model as $key => $value) {
            $select = $value[0] == $info['model_id']?'selected="selected"':'';
            $models .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        /*分类*/
        $Category = M('category');
        $result_category = $Category->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        $categories = '';
        foreach ($result_category as $key => $value) {
            $select = $value[0] == $info['model_id']?'selected="selected"':'';
            $categories .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }

        /*故障*/
        $Failure = M('failure');
        $result_failure = $Failure->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        $failures = '';
        foreach ($result_failure as $key => $value) {
            $select = $value[0] == $info['model_id']?'selected="selected"':'';
            $failures .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        //配置字段
        $this->tca = array(
            'brand_id' => array(
                'label' => '品牌',
                'type' => 'select_tree',
                'data' => $brands,
                'required' => true,
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'model_id' => array(
                'label' => '型号',
                'type' => 'select_tree',
                'data' => $models,
                'required' => true,
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'category_id' => array(
                'label' => '故障类型',
                'type' => 'select_tree',
                'data' => $categories,
                'required' => true,
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'failure_id' => array(
                'label' => '故障',
                'type' => 'select_tree',
                'data' => $failures,
                'required' => true,
                'disabled' => ACTION_NAME == 'edit'?true:false
            ),
            'origin_price' => array(
                'label' => '原价',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/(^[0-9]+$)|(^[0-9]+[\.]{1}[0-9]{1,2}$)/','请输入正确的原价'],
                ],
                'help' => '价格为整数或精确到小数点后一位或两位的数值'
            ),
            'sale_price' => array(
                'label' => '现价',
                'type' => 'text',
                'required' => true,
                'validate' => [
                    ['/(^[0-9]+$)|(^[0-9]+[\.]{1}[0-9]{1,2}$)/','请输入正确的现价'],
                ],
                'help' => '价格为整数或精确到小数点后一位或两位的数值'
            )
        );
    }

    /**
     * 列表页面
     */
    public function index() {
        $this->init(); //加载初始化数据
        $Obj = D($this->tbName); //实例化对象

        $Where = "deleted=0";
        //品牌
        if(I('request.brand_id')){
            $Where .= " and brand_id=".I('request.brand_id');
        }
        //机型
        if(I('request.model_id')){
            $Where .= " and model_id=".I('request.model_id');
        }
        //分类
        if(I('request.category_id')){
            $Where .= " and category_id=".I('request.category_id');
        }

        /*品牌*/
        $Brands = M('brand');
        $result_brand = $Brands->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        $brands = '';
        foreach ($result_brand as $key => $value) {
            $select = $value[0] == I('request.brand_id')?'selected="selected"':'';
            $brands .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        $this->assign('brand_html',$brands);
        /*机型*/
        $Model = M('model');
        $models = '';
        $result_model = $Model->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        foreach ($result_model as $key => $value) {
            $select = $value[0] == I('request.model_id')?'selected="selected"':'';
            $models .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        $this->assign('model_html',$models);
        /*分类*/
        $Category = M('category');
        $result_category = $Category->where(array('deleted' => 0))->Field('id as "0", name as "1"')->order('sorting asc')->select();
        $categories = '';
        foreach ($result_category as $key => $value) {
            $select = $value[0] == I('request.category_id')?'selected="selected"':'';
            $categories .= '<option value="'.$value[0].'"'.$select.'>'.$value[1].'</option>';
        }
        $this->assign('category_html',$categories);
        if(I('post.limit_num') != ''){
            session('page_limit_num', I('post.limit_num'));
        }
        $sorting = I('get.sorting') ? I('get.sorting') : 'id';
        $order = I('get.order') ? I('get.order') : 'desc';
        $limit_num = $_SESSION['page_limit_num'] ? $_SESSION['page_limit_num'] : 10;
        
        $Page = new Page($Obj->where($Where)->count(), $limit_num); // 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Obj->where($Where)->order($sorting . ' ' . $order)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $Page->show()); // 分页显示输出 
        $this->display(); // 输出模板
    }

    /**
     * 编辑数据
     */
    public function edit() {
        $this->save();
    }
    /**
     * 保存数据
     */
    public function save() {
        try{
            $this->init();
            //编辑数据
            $id = I('request.id') ? I('request.id') : null;
            $info = M($this->tbName)->where('id = ' . $id)->find();
            if (IS_POST) {
                foreach ($_POST as $key => $val) {
                    if(is_array($val)){
                        $_POST[$key] = implode(',', $val);
                    }
                    if(@$this->tca[$key]['required'] && !$val){
                        $this->error($this->tca[$key]['label'] . '*是必填项!');
                    }
                    //数据验证
                    if(isset($this->tca[$key]['validate'])){
                        //是否存在关联数据
                        if(isset($this->tca[$key]['relation'])){
                            //判断关联数据值类型 进入不同的判断表达式 只支持字符串，数组两种类型
                            if(is_array($this->tca[$key]['relation'][1])){
                                if(in_array($_POST[$this->tca[$key]['relation'][0]],$this->tca[$key]['relation'][1])){
                                    foreach ($this->tca[$key]['validate'] as $value) {
                                        if(!preg_match($value[0], $val)){
                                            $this->error($value[1]);
                                        }
                                    }
                                }
                            }else{
                                if($_POST[$this->tca[$key]['relation'][0]] == $this->tca[$key]['relation'][1]){
                                    foreach ($this->tca[$key]['validate'] as $value) {
                                        if(!preg_match($value[0], $val)){
                                            $this->error($value[1]);
                                        }
                                    }
                                }
                            }
                        }else{
                            foreach ($this->tca[$key]['validate'] as $value) {
                                if(!preg_match($value[0], $val)){
                                    $this->error($value[1]);
                                }
                            }
                        }
                    }
                }
                $Obj = D($this->tbName);
                $result = $Obj->create();
                if (!$result) {
                    $this->error($Obj->getError());
                } else {        
                    if ($id) {
                        $Obj->tstamp = time();
                        $id = $Obj->where(array('id' => $id))->save();
                        $message = '编辑成功!';
                    } else {
                        $Obj->crdate = time();
                        $Obj->tstamp = time();
                        $id = $Obj->add();
                        $message = '添加成功!';
                    }
                    if($id){
                        $this->success($message, U(CONTROLLER_NAME . '/index', 'kept=1'));
                        exit;
                    }else{
                        debug($Obj->_sql());
                        $this->error('保存失败');
                        exit;
                    }
                    
                }
            }
            //自动渲染字段
            parent::autoFields($this->tca, $info);
            $this->display('info');
        }catch(\Exception $e){
            debug($e->getmessage());
            $message = IS_AJAX?'保存失败':'';
            $this->error($message);
        }
    }

    /*根据品牌获取机型*/
    public function getModels(){
        $brand_id = I('param.brand_id');
        $model_html = '';
        //获取所有该品牌所有的机型
        $Obj = M('model');
        $where = array('deleted' => 0,'brand_id' => $brand_id);
        $models = $Obj->where($where)->select();
        foreach ($models as $key => $value) {
            $selected = $key == 0?'selected="selected"':'';
            $model_html .= "<option value='".$value['id']."' ".$selected.">".$value['name']."</option>";
        }
        echo $model_html;
    }

    /*根据品牌,机型,故障分类获取未录入的故障*/
    public function getFailures(){
        $brand_id = I('param.brand_id');
        $model_id = I('param.model_id');
        $category_id = I('param.category_id');
        $failure_html = '';
        //获取所有该品牌,机型,故障下已经录入的故障
        $Obj = M($this->tbName);
        $where = array('deleted' => 0,'brand_id' => $brand_id,'model_id' => $model_id,'category_id' => $category_id);
        $result = $Obj->where($where)->Field('failure_id')->select();
        $failure_id = [];
        $failure_id = array_map(function($value){
            return $failure_id[] = $value['failure_id'];
        }, $result);
        $where = [
            'deleted' => 0,
            'category_id' => $category_id
        ];
        if($failure_id){
            $where['id'] = ['not in',$failure_id];
        }
        $failures = M('failure')->where($where)->select();
        foreach ($failures as $key => $value) {
            $selected = $key == 0?'selected="selected"':'';
            $failure_html .= "<option value='".$value['id']."' ".$selected.">".$value['name']."</option>";
        }
        echo $failure_html;
    }
}

?>